<?php

namespace App\Http\Middleware;

use Closure;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;

class JWTAuthenticate extends BaseMiddleware
{
    /**
     * @param $request
     * @param Closure $next
     * @param string|null $guard
     * @return mixed
     */
    public function handle($request, Closure $next, ?string $guard)
    {
        $this->checkForToken($request);
        try {
            if (!auth($guard)->check()) {
                throw new UnauthorizedHttpException('jwt-auth', 'Unauthenticated.', null, 401);
            }
            if ($payload = auth($guard)->payload()) {
                if (strpos($payload->get('guard'), $guard) === false) {
                    throw new UnauthorizedHttpException('jwt-auth', 'Unauthenticated.', null, 401);
                }
                app('auth')->shouldUse($guard);
                return $next($request);
            }
        } catch (TokenExpiredException $e) {
            try {
                $token = auth($guard)->refresh();
                auth($guard)->onceUsingId(auth($guard)->payload()->get('sub'));
                return $this->setAuthenticationHeader($next($request), $token);
            } catch (JWTException $e) {
                throw new UnauthorizedHttpException('jwt-auth', $e->getMessage(), $e, $e->getCode());
            }
        } catch (JWTException $e) {
            throw new UnauthorizedHttpException('jwt-auth', $e->getMessage(), $e, $e->getCode());
        }
        return $next($request);
    }
}
